// pages/wishlist/wishlist.js
import { wishList, collectGoods } from '../../../api.js'
Page({
  data: {
    wishList: [{}], //心愿单列表
  },

  onLoad: function (options) {
    let business_id = getApp().globalData.Store.business.id;
    let token = getApp().globalData.Store.token;
    wishList({ business_id, token }).then(res => {
      if (res.data.code == 666) {
        res.data.data.forEach(item => {
          item.user_wishlist = 1
        })
        this.setData({
          wishList: res.data.data
        })
      }
    })
  },
  onShow() {
    getApp().startpage(new Date().getTime())
    let business_id = getApp().globalData.Store.business.id;
    let token = getApp().globalData.Store.token;
    wishList({ business_id, token }).then(res => {
      if (res.data.code == 666) {
        res.data.data.forEach(item => {
          item.user_wishlist = 1
        })
        this.setData({
          wishList: res.data.data
        })
      }
    })
  },
  collect(e) {
    let product_id = String(e.currentTarget.dataset.id);
    let token = getApp().globalData.Store.token;
    let index = e.currentTarget.dataset.ind;
    collectGoods({ product_id, token }).then(res => {
      if (res.data.code == 666) {
        let user_wishlist = 'wishList[' + index + '].user_wishlist';
        this.setData({
          [user_wishlist]: this.data.wishList[index].user_wishlist == 1 ? 0 : 1
        })
        if (this.data.wishList[index].user_wishlist == 0) {
          wx.showToast({
            title: '已取消收藏',
            icon: 'none',
          })
        } else if (this.data.wishList[index].user_wishlist == 1) {
          wx.showToast({
            title: '已成功收藏',
            icon: 'none',
          })
        }
      }
    })
  },
  onHide() {
    getApp().endpage(new Date().getTime())
  }
})